package com.example.redpagehelper.services

import android.accessibilityservice.AccessibilityService
import android.app.Notification
import android.app.PendingIntent
import android.content.Intent
import android.os.CountDownTimer
import android.os.Handler
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.Toast


/**
 *   disableSelf()：禁用当前服务，也就是在服务可以通过该方法停止运行
 *   findFoucs(int falg)：查找拥有特定焦点类型的控件
 *   getRootInActiveWindow()：如果配置能够获取窗口内容,则会返回当前活动窗口的根结点
 *   getSeviceInfo()：获取当前服务的配置信息
 *   onAccessibilityEvent(AccessibilityEvent event)：有关AccessibilityEvent事件的回调函数，系统通过sendAccessibiliyEvent()不断的发送AccessibilityEvent到此处
 *   performGlobalAction(int action)：执行全局操作，比如返回，回到主页，打开最近等操作
 *   setServiceInfo(AccessibilityServiceInfo info)：设置当前服务的配置信息
 *   getSystemService(String name)：获取系统服务
 *   onKeyEvent(KeyEvent event)：如果允许服务监听按键操作，该方法是按键事件的回调，需要注意，这个过程发生了系统处理按键事件之前
 *   onServiceConnected()：系统成功绑定该服务时被触发，也就是当你在设置中开启相应的服务，系统成功的绑定了该服务时会触发，通常我们可以在这里做一些初始化操作
 *   onInterrupt()：服务中断时的回调
 */
class QHBService : AccessibilityService() {

    companion object {
        const val WeChat_ChatUI = "com.tencent.mm.ui.LauncherUI"
        const val WeChat_ReceiveUI = "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyNotHookReceiveUI"
        const val WeChat_DETAIL_UI = "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyDetailUI"


        const val BACK_HOME_TIME = 15000L
        const val RECYCLER_CHECK_INTERVAL = 2000L
    }

    private val countDownTimer = object : CountDownTimer(BACK_HOME_TIME, RECYCLER_CHECK_INTERVAL) {
        override fun onFinish() {
            Log.i("yanze", "onFinish: 返回桌面！")
            handler.removeCallbacksAndMessages(null)
            backToHome()
        }

        override fun onTick(millisUntilFinished: Long) {
            Log.i("yanze", "onTick: 检查...${currentUI}")
            when (currentUI) {
                WeChat_ChatUI -> {
                    cycleFindRedPackage(rootInActiveWindow, groupRule = ::findRedPackage)
                }
                WeChat_ReceiveUI -> {
                    cycleFindRedPackage(rootInActiveWindow, viewRule = ::findKAI)
                }
                WeChat_DETAIL_UI -> {
                    cycleFindRedPackage(rootInActiveWindow, viewRule = ::back)
                }
            }
        }
    }

    private val handler = Handler()

    private var currentUI = ""

    //中断服务回调
    override fun onInterrupt() {
        Toast.makeText(baseContext, "服务中断！！！", Toast.LENGTH_LONG).show()
        Log.e("yanze", "onInterrupt: 服务中断!!！")
    }

    /**
     * getEventType()：事件类型
     * getSource()：获取事件源对应的结点信息
     * getClassName()：获取事件源对应类的类型，比如点击事件是有某个Button产生的，那么此时获取的就是Button的完整类名
     * getText()：获取事件源的文本信息，比如事件是有TextView发出的,此时获取的就是TextView的text属性。如果该事件源是树结构，那么此时获取的是这个树上所有具有text属性的值的集合
     * isEnabled()：事件源(对应的界面控件)是否处在可用状态
     * getItemCount()：如果事件源是树结构，将返回该树根节点下子节点的数量
     */
    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        when (event.eventType) {
            AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED -> {
                Log.i("yanze", "通知栏事件: ")
                event.text.forEach {
                    Log.i("yanze", "onAccessibilityEvent: $it")
                }
                event.text.find { it.toString().contains("[微信红包]") }?.let {
                    if (event.parcelableData != null && event.parcelableData is Notification) {
                        val pendingIntent: PendingIntent = (event.parcelableData as Notification).contentIntent
                        pendingIntent.send()
                    }
                }
            }
            AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
                Log.i("yanze", "窗口变化事件: ")
                val className = event.className.toString()
                currentUI = className
                Log.i("yanze", "onAccessibilityEvent: 类名：${className}")
                handler.removeCallbacksAndMessages(null)
                countDownTimer.cancel()
                countDownTimer.start()
                when (className) {
                    WeChat_ChatUI -> { // 聊天页面
                        Log.i("yanze", "onAccessibilityEvent: 聊天页面-->\n")
                        cycleFindRedPackage(rootInActiveWindow, groupRule = ::findRedPackage)
                    }
                    WeChat_ReceiveUI -> { // 红包页🧧
                        Log.i("yanze", "onAccessibilityEvent: 红包页-->\n")
                        cycleFindRedPackage(rootInActiveWindow, viewRule = ::findKAI)
                    }
                    WeChat_DETAIL_UI -> { // 红包详情页
                        Log.i("yanze", "onAccessibilityEvent: 红包详情页-->\n")
                        cycleFindRedPackage(rootInActiveWindow, groupRule = ::back)
                    }
                }
            }
        }
    }

    // ================================= 微信界面按钮规则 ========================================
    /**
     * 聊天页：找未领取的红包,并进入
     */
    fun findRedPackage(nodeInfo: AccessibilityNodeInfo): Boolean {
        if (nodeInfo.className.contains("FrameLayout") && nodeInfo.isClickable) {
            var redPackageDesc = ""
            for (i in 0 until nodeInfo.childCount) {
                if (i != 0) {
                    redPackageDesc += nodeInfo.getChild(i)?.text ?: ""
                }
            }
            Log.i("yanze", "是否是红包: ${redPackageDesc}")
            if (redPackageDesc.contains("微信红包") && !redPackageDesc.contains("已领取") && !redPackageDesc.contains("被领完")) {
                Log.i("yanze", "进入红包～")
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                handler.postDelayed({ nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK) }, 500)
                return true
            }
        }
        return false
    }

    /**
     * 未领取红包页：找到"开"并点击
     */
    fun findKAI(nodeInfo: AccessibilityNodeInfo): Boolean {
        return if ((nodeInfo.contentDescription
                        ?: "").toString().contains("开") && nodeInfo.isClickable) {
            Log.i("yanze", "点击\"开\" 开红包～: ")
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK)
            true
        } else false
    }

    /**
     * 红包详情页（领取后）：找到返回并点击
     */
    fun back(nodeInfo: AccessibilityNodeInfo): Boolean {
        if (nodeInfo.className.contains("LinearLayout") && nodeInfo.isClickable) {
            var viewDesc = ""
            for (i in 0 until nodeInfo.childCount) {
                viewDesc += nodeInfo.getChild(i)?.contentDescription ?: ""
            }
            Log.i("yanze", "是否是返回: $viewDesc")
            if (viewDesc.contains("返回")) {
                Log.i("yanze", "点击图标 返回之～: ")
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                return true
            }
        }
        return false
    }
    // ================================= 微信界面按钮规则end ========================================

    /**
     * 递归遍历传入窗口View树
     * 缺点：某一规则生效后，不能彻底退出递归
     */
    private fun cycleFindRedPackage(nodeInfo: AccessibilityNodeInfo?, groupRule: ((nodeInfo: AccessibilityNodeInfo) -> Boolean)? = null, viewRule: ((nodeInfo: AccessibilityNodeInfo) -> Boolean)? = null) {
        if (nodeInfo == null) return
        if (nodeInfo.childCount == 0) {
//            Log.i("yanze", "单个View: ${nodeInfo.className} ${nodeInfo.contentDescription} ${nodeInfo.text} ${nodeInfo.isClickable}")
            if (viewRule?.invoke(nodeInfo) == true) {
                return
            }
        } else {
            if (groupRule?.invoke(nodeInfo) == true) {
                return
            }
//            Log.i("yanze", "ViewGroup组：${nodeInfo.className} ${nodeInfo.contentDescription} ${nodeInfo.text} ${nodeInfo.childCount} ${nodeInfo.isClickable}")
            for (i in 0 until nodeInfo.childCount) {
                val node = nodeInfo.getChild(i)
                cycleFindRedPackage(node, groupRule, viewRule)
            }
        }
    }


    private fun backToHome() {
        val intent = Intent(Intent.ACTION_MAIN)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.addCategory(Intent.CATEGORY_HOME)
        startActivity(intent)
    }


    //    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    //    private fun inputClick(clickId: String) {
    //        val nodeClick = rootInActiveWindow?.findAccessibilityNodeInfosByViewId(clickId)
    //        nodeClick?.forEach { it.performAction(AccessibilityNodeInfo.ACTION_CLICK) }
    //    }

    //    val nodeInfos = ArrayList<AccessibilityNodeInfo>()
    //    private fun cycleWindowUI(rootNodeInfo: AccessibilityNodeInfo?, function: () -> Unit): AccessibilityNodeInfo? {
    //        nodeInfos.clear()
    //        if (rootNodeInfo == null) return null
    //        for (i in 0 until rootNodeInfo.childCount) {
    //            nodeInfos.add(rootNodeInfo.getChild(i))
    //        }
    //        var index = 0
    //        while (index < nodeInfos.size) {
    //            if (nodeInfos[index].childCount == 0) {
    //                Log.i("yanze", "only View: ${nodeInfos[index].className.toString()} ${nodeInfos[index].contentDescription} ${nodeInfos[index].text} ${nodeInfos[index].isClickable}")
    //            } else {
    //                Log.i("yanze", "ViewGroup：${nodeInfos[index].className.toString()} ${nodeInfos[index].contentDescription} ${nodeInfos[index].text} ${nodeInfos[index].childCount} ${nodeInfos[index].isClickable}")
    //                for (i in 0 until nodeInfos[index].childCount) {
    //                    nodeInfos.add((index + 1), nodeInfos[index].getChild(i))
    //                }
    //            }
    //            index++
    //        }
    //        Log.i("yanze", "cycleWindowUI: 共${index - 1}个节点")
    //        return null
    //    }

}